/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controleur;

import application.Facade;
import application.beans.CompteBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Étienne
 */
public class ServCreationCompte extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NoSuchAlgorithmException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();
        Facade f = new Facade();
        
        String next = ConstantesWeb.ATTRIBUT_PAGE_GESTIONCOMPTE;
        List<CompteBean> resultats = null;
        CompteBean nouveau = new CompteBean();
        
        String username = request.getParameter("nouveauUsername");
        String prenom   = request.getParameter("nouveauPrenom");
        String nom      = request.getParameter("nouveauNom");
        String code     = request.getParameter("nouveauCode");
        String courriel = request.getParameter("nouveauCourriel");
        String domaine  = request.getParameter("nouveauDomaine");
        String statut   = request.getParameter("nouveauStatut");
        String password = request.getParameter("nouveauPassword");
        
        // On ajoute les informations au compte
        if(username != null){nouveau.setUsername(f.decoderChaine(username));}
                        else{nouveau.setUsername("");}
        if(prenom != null){nouveau.setPrenom(f.decoderChaine(prenom));}
                        else{nouveau.setPrenom("");}
        if(nom != null){nouveau.setNom(f.decoderChaine(nom));}
                        else{nouveau.setNom("");}
        if(code != null){nouveau.setCodePermanent(f.decoderChaine(code));}
                        else{nouveau.setCodePermanent("");}
        if(courriel != null){nouveau.setCourriel(f.decoderChaine(courriel));}
                        else{nouveau.setCourriel("");}
        if(domaine != null){nouveau.setDomaineEtude(f.decoderChaine(domaine));}
                        else{nouveau.setDomaineEtude("");}
        if(statut != null){nouveau.setStatut(f.decoderChaine(statut));}
                        else{nouveau.setStatut("");}
        nouveau.setSexe(request.getParameter("nouveauSexe"));
        
        // On encrypte le mot de passe
        try {
            MessageDigest md = MessageDigest.getInstance("MD5"); 
            byte[] messageDigest = md.digest(password.getBytes());  
            BigInteger number = new BigInteger(1, messageDigest);   
            String hashtext = number.toString(16);         
            // Now we need to zero pad it if you actually want the full 32 chars.   
            while (hashtext.length() < 32) {         
                hashtext = "0" + hashtext;          
            }       
            password = hashtext;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ServLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // On écris le nouveau compte
        f.ecrireCompte(nouveau, password);
        
        // On va chercher les résultats mis à jour de la recherche
        CompteBean criteres = (CompteBean)session.getAttribute(ConstantesWeb.ATTRIBUT_CRITERES_GESTION_COMPTE);
        // Si un critère est null plutôt que vide, il n'y a pas de critères
        if(criteres.getUsername() != null){
            resultats = f.rechercheComptesAvancee(criteres);
            session.setAttribute(ConstantesWeb.ATTRIBUT_RESULTAT_GESTION_COMPTE, resultats);
        }        
        
        RequestDispatcher rd = getServletContext().getRequestDispatcher(next);
        rd.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ServCreationCompte.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(ServCreationCompte.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
